package com.lvcoding.client.gitee.config;

import com.lvcoding.client.gitee.domain.CustomOAuth2User;
import com.lvcoding.client.gitee.domain.GiteeOAuth2User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.annotation.Resource;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private GiteeOAuth2AccessTokenResponseClient accessTokenResponseClient;

    @Resource
    private GiteeOAuth2UserService oAuth2UserService;

    @Resource
    private CustomOAuth2UserService customOAuth2UserService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return new InMemoryUserDetailsManager(
                User.withUsername("admin")
                        .password(passwordEncoder().encode("admin"))
                        .roles("user")
                        .build()
        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login/gitee").loginProcessingUrl("/login/form")
                .and()
                .authorizeRequests()
                .antMatchers("/hello").hasAnyAuthority("ROLE_USER")
                .antMatchers("/**").permitAll()
                .and()
                .logout().deleteCookies("JSESSIONID")
                .logoutSuccessUrl("/").permitAll();

        http.oauth2Login().loginPage("/login/gitee")
                .tokenEndpoint().accessTokenResponseClient(accessTokenResponseClient)
                .and()
                .userInfoEndpoint()
                .customUserType(GiteeOAuth2User.class, "gitee")
                .customUserType(CustomOAuth2User.class, "myauth")
                .userService(customOAuth2UserService)
                .userService(oAuth2UserService);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder());
    }

}
